// dh-pricing 云对象 - 统一价格计算服务
const db = uniCloud.database();
const _ = db.command;

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-pricing] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 获取基础价格
 * @param {number} targetType - 目标类型（1-服务，2-产品，3-医生）
 * @param {string} targetId - 目标ID
 */
async function getBasePrice(targetType, targetId) {
	let collection, priceField;
	
	switch(targetType) {
		case 1: // 服务
			collection = 'dh-services';
			priceField = 'base_price';
			break;
		case 2: // 产品
			collection = 'dh-products';
			priceField = 'price';
			break;
		case 3: // 医生咨询费
			collection = 'dh-doctors';
			priceField = 'consultation_fee';
			break;
		default:
			throw new Error('不支持的目标类型');
	}
	
	const res = await db.collection(collection).doc(targetId).field({ [priceField]: true }).get();
	if (res.data.length === 0) {
		throw new Error('目标对象不存在');
	}
	
	return res.data[0][priceField] || 0;
}

/**
 * 获取当前生效的促销规则
 * @param {number} targetType - 目标类型
 * @param {string} targetId - 目标ID
 */
async function getActivePromotionRules(targetType, targetId) {
	const today = new Date().toISOString().split('T')[0];
	
	// 查询条件：
	// 1. 状态为启用
	// 2. 目标类型匹配
	// 3. 当前日期在有效期内
	// 4. target_ids为空或包含当前targetId
	const res = await db.collection('dh-promotion_rules')
		.where({
			target_type: targetType,
			status: 1,
			start_date: _.lte(today),
			end_date: _.gte(today)
		})
		.orderBy('priority', 'desc')
		.get();
	
	// 过滤出适用于当前targetId的规则
	const applicableRules = res.data.filter(rule => {
		// 如果target_ids为空或不存在，表示适用于所有对象
		if (!rule.target_ids || rule.target_ids.length === 0) {
			return true;
		}
		// 如果target_ids包含当前targetId，则适用
		return rule.target_ids.includes(targetId);
	});
	
	return applicableRules;
}

/**
 * 应用促销规则计算折扣价格
 * @param {number} basePrice - 基础价格
 * @param {array} rules - 促销规则列表（已按优先级排序）
 * @param {number} quantity - 数量
 */
function applyPromotionRules(basePrice, rules, quantity = 1) {
	if (!rules || rules.length === 0) {
		return {
			basePrice: basePrice,
			finalPrice: basePrice * quantity,
			discount: 0,
			savingAmount: 0,
			promotionInfo: null
		};
	}
	
	// 选择优先级最高的规则
	const bestRule = rules[0];
	let discountAmount = 0;
	let finalPrice = basePrice * quantity;
	
	switch(bestRule.discount_type) {
		case 1: // 百分比折扣
			discountAmount = basePrice * quantity * (1 - bestRule.discount_value);
			finalPrice = basePrice * quantity * bestRule.discount_value;
			break;
			
		case 2: // 固定金额减免
			discountAmount = bestRule.discount_value;
			finalPrice = Math.max(0, basePrice * quantity - bestRule.discount_value);
			break;
			
		case 3: // 满减优惠
			if (basePrice * quantity >= bestRule.min_purchase_amount) {
				discountAmount = bestRule.discount_value;
				finalPrice = basePrice * quantity - bestRule.discount_value;
			}
			break;
			
		case 4: // 特价
			if (bestRule.special_price) {
				discountAmount = (basePrice - bestRule.special_price) * quantity;
				finalPrice = bestRule.special_price * quantity;
			}
			break;
	}
	
	// 应用最大优惠封顶
	if (bestRule.max_discount_amount && discountAmount > bestRule.max_discount_amount) {
		discountAmount = bestRule.max_discount_amount;
		finalPrice = basePrice * quantity - discountAmount;
	}
	
	// 确保最终价格不为负数
	finalPrice = Math.max(0, finalPrice);
	
	return {
		basePrice: basePrice,
		finalPrice: parseFloat(finalPrice.toFixed(2)),
		discount: parseFloat(discountAmount.toFixed(2)),
		savingAmount: parseFloat(discountAmount.toFixed(2)),
		promotionInfo: {
			ruleName: bestRule.rule_name || '优惠活动',
			description: bestRule.description || '',
			discountType: bestRule.discount_type
		}
	};
}

module.exports = {
	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();
		console.log(`[dh-pricing] 调用方法: ${methodName}, 用户ID: ${uniIdToken?.uid}`);
	},

	/**
	 * 计算单个项目的价格
	 * @param {number} targetType - 目标类型（1-服务，2-产品，3-医生咨询费）
	 * @param {string} targetId - 目标ID
	 * @param {number} quantity - 数量，默认为1
	 */
	async calculatePrice(targetType, targetId, quantity = 1) {
		try {
			if (!targetType || !targetId) {
				return formatResponse(400, null, '目标类型和ID不能为空');
			}
			
			quantity = parseInt(quantity) || 1;
			
			// 1. 获取基础价格
			const basePrice = await getBasePrice(targetType, targetId);
			
			// 2. 获取生效的促销规则
			const rules = await getActivePromotionRules(targetType, targetId);
			
			// 3. 应用促销规则计算最终价格
			const priceInfo = applyPromotionRules(basePrice, rules, quantity);
			
			return formatResponse(200, priceInfo);
		} catch (error) {
			return formatError(error, '价格计算失败');
		}
	},

	/**
	 * 批量计算多个项目的价格
	 * @param {array} items - 项目列表 [{targetType, targetId, quantity}, ...]
	 */
	async calculateBatch(items) {
		try {
			if (!Array.isArray(items) || items.length === 0) {
				return formatResponse(400, null, '项目列表不能为空');
			}
			
			const promises = items.map(item => 
				this.calculatePrice(item.targetType, item.targetId, item.quantity || 1)
			);
			
			const results = await Promise.all(promises);
			
			// 提取所有成功的价格信息
			const priceInfos = results.map(result => result.data).filter(data => data !== null);
			
			// 计算总计
			const totalBase = priceInfos.reduce((sum, info) => sum + (info.basePrice * (info.quantity || 1)), 0);
			const totalFinal = priceInfos.reduce((sum, info) => sum + info.finalPrice, 0);
			const totalSaving = priceInfos.reduce((sum, info) => sum + info.savingAmount, 0);
			
			return formatResponse(200, {
				items: priceInfos,
				summary: {
					totalBasePrice: parseFloat(totalBase.toFixed(2)),
					totalFinalPrice: parseFloat(totalFinal.toFixed(2)),
					totalSaving: parseFloat(totalSaving.toFixed(2))
				}
			});
		} catch (error) {
			return formatError(error, '批量价格计算失败');
		}
	},

	/**
	 * 获取指定对象的所有生效促销规则
	 * @param {number} targetType - 目标类型
	 * @param {string} targetId - 目标ID（可选，不传则返回该类型的所有规则）
	 */
	async getActiveRules(targetType, targetId = null) {
		try {
			if (!targetType) {
				return formatResponse(400, null, '目标类型不能为空');
			}
			
			const today = new Date().toISOString().split('T')[0];
			
			let query = {
				target_type: targetType,
				status: 1,
				start_date: _.lte(today),
				end_date: _.gte(today)
			};
			
			const res = await db.collection('dh-promotion_rules')
				.where(query)
				.orderBy('priority', 'desc')
				.get();
			
			let rules = res.data;
			
			// 如果提供了targetId，过滤出适用的规则
			if (targetId) {
				rules = rules.filter(rule => {
					if (!rule.target_ids || rule.target_ids.length === 0) {
						return true;
					}
					return rule.target_ids.includes(targetId);
				});
			}
			
			return formatResponse(200, rules, 'success', { count: rules.length });
		} catch (error) {
			return formatError(error, '获取促销规则失败');
		}
	},

	/**
	 * 预览促销规则效果
	 * @param {number} basePrice - 基础价格
	 * @param {string} ruleId - 规则ID
	 * @param {number} quantity - 数量
	 */
	async previewRuleEffect(basePrice, ruleId, quantity = 1) {
		try {
			if (!basePrice || !ruleId) {
				return formatResponse(400, null, '基础价格和规则ID不能为空');
			}
			
			const res = await db.collection('dh-promotion_rules').doc(ruleId).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '规则不存在');
			}
			
			const rule = res.data[0];
			const priceInfo = applyPromotionRules(basePrice, [rule], quantity);
			
			return formatResponse(200, priceInfo);
		} catch (error) {
			return formatError(error, '预览规则效果失败');
		}
	}
};

